package models

import (
	"go/ast"
	"regexp"
)

const (
	AnnotationName = "name" //entityName
)

type Annotation struct {
	Name  string
	Value string
}

func NewAnnotation(annotationString string) *Annotation {
	pattern := "// @dal:(\\w+) (\\w+)"
	regex, _ := regexp.Compile(pattern)
	if regex.MatchString(annotationString) {
		matches := regex.FindStringSubmatch(annotationString)
		return &Annotation{
			Name:  matches[1],
			Value: matches[2],
		}
	}
	return nil
}

func NewAnnotations() *Annotations {
	annotations := make(map[string]*Annotation)
	return (*Annotations)(&annotations)
}

type Annotations map[string]*Annotation

func (a *Annotations) Visit(node ast.Node) ast.Visitor {
	switch n := node.(type) {
	case *ast.Comment:
		annotation := NewAnnotation(n.Text)
		if annotation != nil {
			(*a)[annotation.Name] = annotation
		}
		return nil
	}
	return a
}

func (a *Annotations) Get(name string) (*Annotation, bool) {
	if v, exist := (*a)[name]; exist {
		return v, exist
	}
	return nil, false
}

func (a *Annotations) Set(name, value string) {
	(*a)[name] = &Annotation{
		Name:  name,
		Value: value,
	}
}

func (a *Annotations) Len() int {
	return len(*a)
}
